package com.nowcoder.community.service.impl;

import com.nowcoder.community.dao.CommentMapper;
import com.nowcoder.community.dao.DiscussPostMapper;
import com.nowcoder.community.entity.Comment;
import com.nowcoder.community.service.CommentService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.SensitiveFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
public class CommentServiceImpl implements CommentService, CommunityConstant {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private DiscussPostMapper discussPostMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Override
    public List<Comment> findCommentByEntity(int entityType, int entityId, int offset, int limit) {
        return commentMapper.selectCommentByEntity(entityType, entityId, offset, limit);
    }

    @Override
    public int findCommentCount(int entityType, int entityId) {
        return commentMapper.selectCountByEntity(entityType, entityId);
    }

    /**
     * 同时执行两个DataBase的操作
     * 向comment中插入一条新数据
     * 更新discuss_post中的comment_count字段
     * 所以要进行事务管理
     * 有一个操作失败，则两个操作带来的数据变化全部回滚
     * @param comment
     * @return
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public int addComment(Comment comment) {
        if(comment == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        // 过滤comment中的html标签
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        // 过滤敏感词
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        int rows = commentMapper.insertComment(comment);

        // 更新评论目标帖子的comment_count
        // 只有评论目标是帖子时才更新 -> entity_type = 1
        if(comment.getEntityType() == ENTITY_TYPE_POST) {
            int commentCnt = commentMapper.selectCountByEntity(comment.getEntityType(), comment.getEntityId());
            // 此处不需要+1
            // 因为新的comment先被插入了
            discussPostMapper.updateCommentCount(comment.getEntityId(), commentCnt);
        }
        return rows;
    }

    @Override
    public Comment findCommentById(int commentId) {
        return commentMapper.selectCommentById(commentId);
    }
}
